from django.db import models

# Create your models here.
from airconfig.config import config
from django.urls import path, include
from django.http import HttpResponse, JsonResponse
from scheduler.schedule import Request
import json
from adm.views import room_list
from adm.models import master
from scheduler.schedule import sche
from common.models import Detail, Customer
from .views import customer
from datetime import datetime
from django.core import signing




# 控制器
class Customer_Controller():
    def get_request(self):
        urlpatterns=[
            path('poweroff/', self.poweroff),
            path('poweron/', self.poweron),
            path('changetargettemp/', self.changetargettemp),
            path('changefanspeed/', self.changefanspeed),
            path('requeststate/', self.requeststate),
            path('signup/', customer.signup),
        ]

    def checktoken(self,request):
        # 用户的token是rid|rid:*****,checkinDate|checkinDate:******
        token = request.META.get("HTTP_AUTHORIZATION")
        splitlist=token.split(',')
        strlist1 = splitlist[0].split('|')
        src1 = signing.loads(strlist1[1])  #rid
        strlist1[0] = strlist1[0].encode("latin1").decode("utf-8")
        strlist2 = splitlist[1].split('|')
        src2 = signing.loads(strlist2[1]) #checkinDate
        strlist2[0] = strlist2[0].encode("latin1").decode("utf-8")
        print("the request include token from",src1['rid'])
        if strlist1[0] == src1['rid'] and strlist2[0] == src2['checkinDate']:
            return 0   #token 正确
        else:
            return 1

    def changetargettemp(self, request):
        request.params = json.loads(request.body)
        roomid = request.params['roomId']
        targetTemp = request.params['targetTemp']
        print("receiving request:change to target temperature\ntarget room:",roomid,",target temperature:",targetTemp)

        return_value = dict()
        flag1=(config.default_work_mode==-1) and (targetTemp > config.cold_sup or targetTemp < config.cold_sub)  #超过制冷温度范围
        flag2=(config.default_work_mode==1) and (targetTemp > config.hot_sup or targetTemp < config.hot_sub)   #超过制热温度范围
        if flag1 or flag2 or (roomid not in config.room_list) or self.checktoken(request):
            print("error occur!")
            return_value['error_code'] = 1
        else:
            request_tmp = sche.get_request(roomid)  #获取当前request
            duration = sche.get_time(roomid)  # 实时获取servicetime
            record = Detail.objects.create(rid=roomid, lastinTime=request_tmp.serviceStartTime,
                                           requestDuration=duration, fanSpeed=request_tmp.fanSpeed,feeRate=config.fee_rates,
                                           fee=request_tmp.feeRate * duration, cmd=" change_tmp",createtime=datetime.now())
            # 虽然记录了详单，但是request详单参数不会进行改变
            request_tmp.targetTemp = targetTemp
            queue_now = sche.get_request_pos(roomid)
            if queue_now == "service":
                if (request_tmp.workmode == 1 and request_tmp.targetTemp > request_tmp.currentTemp) or (
                        request_tmp.workmode == -1 and request_tmp.targetTemp < request_tmp.currentTemp):  # 此处需要换成实时温度
                    sche.one_room_pause(roomid)
            return_value['error_code'] = 0
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def poweron(self, request):
        # 实例化一个新的request,并交给调度
        request.params = json.loads(request.body)
        roomid = request.params['roomId']
        targetTemp = request.params['targetTemp']
        fanspeed = request.params['fanSpeed']
        if fanspeed == "0":
            temprate = config.temp_rate_speed[0]
        elif fanspeed == "1":
            temprate = config.temp_rate_speed[1]
        else:
            temprate = config.temp_rate_speed[2]
        print("receiving request:power on\ntargetroom:",roomid,",target temperature:",targetTemp,",target fan speed:",fanspeed )
        return_value = dict()
        flag1 = (config.default_work_mode == -1) and (
                    targetTemp > config.cold_sup or targetTemp < config.cold_sub)  # 超过制冷温度范围
        flag2 = (config.default_work_mode == 1) and (
                    targetTemp > config.hot_sup or targetTemp < config.hot_sub)  # 超过制热温度范围
        queue_now = sche.get_request_pos(roomid)  # 如果为None，说明不在任意一个队列，说明没有正在工作
        if flag1 or flag2 or \
                (roomid not in config.room_list) or queue_now != None or self.checktoken(request):
            print("error occur!")
            return_value['error_code'] = 1
        # 如果接通电源，master的属性有变化，此处需要判断
        else:
            for room in room_list:
                if room.roomid == roomid:
                    print("the room exist!")
                    currenttemp = room.get_current_temp()
                    room.onoff=1
                    request_on = Request(roomid, currenttemp, targetTemp, fanspeed, config.fee_rates,
                                         temprate,config.default_work_mode)
                    #lastinTime 属性无用
                    record = Detail.objects.create(rid=roomid, lastinTime=request_on.serviceStartTime,
                                                   requestDuration=0, fanSpeed=request_on.fanSpeed,feeRate=config.fee_rates,
                                                   fee=0, cmd=" power_on",createtime=datetime.now())
                            # 调用schedule
                    sche.one_room_power_on(request_on)
                    return_value['error_code'] = 0
                    break
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def poweroff(self, request):
        # 生成详单，并且删除request
        request.params = json.loads(request.body)
        roomid = request.params['roomId']
        print("receiving request:poweroff,targetroom:",roomid)
        return_value = dict()
        queue_now = sche.get_request_pos(roomid)  # 如果不为None，说明正在工作
        if (roomid not in config.room_list) or queue_now == None or self.checktoken(request):
            print("error occur!")
            return_value['error_code'] = 1
        else:
            request_off = sche.get_request(roomid)
            duration = sche.get_time(roomid)   # 这应该是实时获取servicetime的函数
            record = Detail.objects.create(rid=roomid, lastinTime=request_off.serviceStartTime,
                                           requestDuration=duration, fanSpeed=request_off.fanSpeed,feeRate=config.fee_rates,
                                           fee=request_off.feeRate * duration, cmd="power_off",createtime=datetime.now())
            # 将当前温度传入到其对应的房间对象中
            for room in room_list:
                if room.roomid == roomid:
                    room.currenttemp = request_off.currentTemp
                    room.lastoff = datetime.now()
                    room.onoff=0
            sche.one_room_power_off(roomid)
            return_value['error_code'] = 0
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def changefanspeed(self, request):
        request.params = json.loads(request.body)
        roomid = request.params['roomId']
        targetFan = request.params['fanSpeed']
        print("receiving request:change to fan speed\ntargetroom:",roomid,",target fan speed:",targetFan)
        return_value = dict()
        queue_now = sche.get_request_pos(roomid)  # 如果不为None，说明正在工作
        flag=targetFan not in config.fan_limit

        if (roomid not in config.room_list) or self.checktoken(request) or queue_now == None or flag:
            print("error occur!")
            if roomid not in config.room_list:
                print("room not exist!")
            if self.checktoken(request):
                print("wrong token!")
            if queue_now == None:
                print("room not working!")
            if flag:
                print("wrong fan speed!")
            return_value['error_code'] = 1
        else:
            request_fan = sche.get_request(roomid)
            duration = sche.get_time(roomid)  # 这应该是实时获取servicetime的函数
            record = Detail.objects.create(rid=roomid, lastinTime=request_fan.serviceStartTime,
                                           requestDuration=duration, fanSpeed=request_fan.fanSpeed,feeRate=config.fee_rates,
                                           fee=request_fan.feeRate * duration, cmd="change_fan",createtime=datetime.now())
            # 修改request详单相关参数,此处需要后续确认
            request.fee = 0
            request_fan.fanSpeed = targetFan
            if request_fan.fanSpeed == "0":
                temprate = config.temp_rate_speed[0]
            elif request_fan.fanSpeed == "1":
                temprate= config.temp_rate_speed[1]
            else:
                temprate = config.temp_rate_speed[2]
            request_fan.tempRate=temprate
            sche.change_fan_speed(roomid)
            return_value['error_code'] = 0
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

    def requeststate(self, request):
        request.params = json.loads(request.body)
        roomid = request.params['roomId']
        print("receiving request:request state,target room:",roomid)
        return_value = dict()
        queue_now = sche.get_request_pos(roomid)  # 如果不为None，说明正在工作
        if (roomid not in config.room_list) or queue_now == None or self.checktoken(request):
            print("error occur!")
            return_value['error_code'] = 1
        else:
            checkindate_list = Customer.objects.filter(rid=roomid).values_list('checkinDate', flat=True)
            if checkindate_list:
                checkindate = max(checkindate_list)
            else:
                checkindate=datetime.now()
            # 从checkinadte到现在所有的detail的fee之和
            detail_list = Detail.objects.filter(rid=roomid, createtime__gt=checkindate).values_list('fee',"cmd")
            sum = 0
            for fee in detail_list:
                if fee[1] in ["power_off","schedule_kick","target_temp","change_fan"]:
                    sum += fee[0]
            request_check = sche.get_request(roomid)
            duration = request_check.serviceTime  # 这应该是实时获取servicetime的函数
            sum += duration * request_check.feeRate
            for room in room_list:
                if room.roomid == roomid:
                    room.totalCost = sum
            return_value['error_code'] = 0
            return_value["data"] = {}
            return_value["data"]['currentTemp'] = request_check.currentTemp
            return_value["data"]['totalFee'] = sum
            return_value["data"]['currentFee'] = request_check.feeRate
        ret = json.dumps(return_value)
        return HttpResponse(content=ret, content_type="application/json")

customer_controller=Customer_Controller()


urlpatterns = [
    path('poweroff', customer_controller.poweroff),
    path('poweron', customer_controller.poweron),
    path('changetargettemp', customer_controller.changetargettemp),
    path('changefanspeed', customer_controller.changefanspeed),
    path('requeststate',customer_controller.requeststate),
    path('signup', customer.signup),
]

